<?php
namespace App\Librarys;

class Curl
{
    /**
     * curl 调用/api统一调用
     * @return $err, $res
     */
    public static  function __callStatic($method, $args)
    {

        $method = strtolower($method);
        if (!in_array($method, ['get', 'post', 'put', 'delete'])) {
            return [1, 'unSupported Method'];
        }
        @list($url, $data, $opts) = $args;

        $ch = curl_init();
        curl_setopt_array($ch, array(
            CURLOPT_TIMEOUT        => 30,
            CURLOPT_URL            => $url,
            CURLOPT_SSL_VERIFYPEER => false,
            CURLOPT_SSL_VERIFYHOST => false,
            CURLOPT_RETURNTRANSFER => 1,
            CURLOPT_USERAGENT      => 'homework',
        ));

        if ($method == 'get') {
            $symbol       = strstr($url, '?') === false ? '?' : '&';
            $data && $url = sprintf("%s{$symbol}%s", $url, http_build_query($data));
        } else {
            $method == 'post' ? curl_setopt($ch, CURLOPT_POST, 1) : curl_setopt($ch, CURLOPT_CUSTOMREQUEST, $method);
            $data && curl_setopt($ch, CURLOPT_POSTFIELDS, http_build_query($data));
        }
        // curl_setopt($ch, CURLOPT_PROXY, "http://127.0.0.1:8888"); //本地fiddler开发调试使用
        curl_setopt($ch, CURLOPT_URL, $url);
        is_null($opts) or curl_setopt_array($ch, $opts);

        $res = curl_exec($ch);

        if (curl_errno($ch)) {
            return [1, 'Curl error: ' . curl_error($ch)];
        }
        curl_close($ch);
        return [0, $res];
    }
}
